package com.wolfalpha.utron.activity;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.adapter.ItemProjectTeamerAdapter;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.Project;
import com.wolfalpha.utron.service.ProjectService;
import com.wolfalpha.utron.service.impl.ProjectServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.StringUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.CircleImageView;
import com.wolfalpha.utron.view.ScrollXListView;

import java.util.List;

/**
 * 项目发布编辑界面
 * <p/>
 * Created by luodon on 15/8/30.
 */
public class ProjectDetailActivity extends Activity implements View.OnClickListener {

    private TextView tvName;        //项目名
    private TextView tvLocation;    //项目地址
    private TextView tvDate;        //项目时间
    private TextView tvAttention;    //项目关注数
    private TextView tvComments;    //项目评论数

    private CheckBox llInfo;    //详细信息
    private CheckBox llPartner; //合伙人

    private TextView vInfo;             //详细信息下栏
    private TextView vPartner;          //合伙人下栏
    /*合伙人信息*/
    private TextView tvCTech;       //召唤技术
    private TextView tvCProduct;    //召唤产品
    private TextView tvCOper;       //召唤运营
    private TextView tvCDesign;     //召唤设计
    private TextView tvCSale;       //召唤销售

    private ScrollXListView lvTeamer;//团队成员

    private ItemProjectTeamerAdapter teamerAdapter;

    private ScrollView svInfo;
    private ScrollView svPartner;

    private TextView tvJlq;         //交流群

    /*详细信息*/
    private TextView tvIntro;       //一句话
    private TextView tvTeamers;     //团队人数
    private TextView tvDir;         //项目方向
    private TextView tvProgress;    //项目进展
    private TextView tvDetail;      //项目详情


    private ImageView ivBack;       //返回
    private ImageView ivCollect;    //收藏

    private CircleImageView cvLogo; //项目LOGO

    private LinearLayout llComment;//评论
    private LinearLayout llAttention;     //关注

    private ProjectService projectService;

    private int pId;                //项目ID
    private Project project;        //全局项目


    private Drawable cTech;
    private Drawable cProduct;
    private Drawable cOper;
    private Drawable cSale;
    private Drawable cDesign;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null || !bundle.containsKey("pId")) {
            finish();
        }
        pId = bundle.getInt("pId");

        setContentView(R.layout.activity_project_detail);

        initView();
        initListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    /**
     * 加载数据
     */
    private void loadData() {
        projectService = new ProjectServiceImpl();

        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                project = projectService.getDetail(pId);
                if (project != null) {
                    handler.sendEmptyMessage(LOAD_FINISH);
                }
                boolean b = projectService.checkAttention(pId);
                if (b) {
                    handler.sendEmptyMessage(CHECK_YES_ATTENTION);
                }

            }
        });
    }


    private final int LOAD_FINISH = 1;
    private final int CHECK_YES_ATTENTION = 2;
    private final int CHECK_NO_ATTENTION = 3;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOAD_FINISH:
                    if (project.getTeamers() != null) {
                        teamerAdapter = new ItemProjectTeamerAdapter(ProjectDetailActivity.this, project.getTeamers());
                        lvTeamer.setAdapter(teamerAdapter);
                    }

                    tvName.setText(project.getName());
                    tvLocation.setText(project.getLocation());
                    tvDate.setText(StringUtils.TimeStamp2Date2(project.getTime() * 1000));

                    tvIntro.setText(project.getIntro());

                    tvAttention.setText(String.valueOf(project.getC_attention()));
                    tvComments.setText(String.valueOf(project.getC_comment()));
                    tvDetail.setText(project.getDetail());

//                    tvCTech.setText(project.getCalls());

                    String string = project.getCalls();
                    if (string != null) {
                        if (string.contains("技术")) {
                            tvCTech.setTextColor(Color.parseColor("#18b4ed"));
                            tvCTech.setCompoundDrawables(null, cTech, null, null);
                        }
                        if (string.contains("产品")) {
                            tvCProduct.setTextColor(Color.parseColor("#18b4ed"));
                            tvCProduct.setCompoundDrawables(null, cProduct, null, null);
                        }
                        if (string.contains("设计")) {
                            tvCDesign.setTextColor(Color.parseColor("#18b4ed"));
                            tvCDesign.setCompoundDrawables(null, cDesign, null, null);
                        }
                        if (string.contains("营销")) {
                            tvCSale.setTextColor(Color.parseColor("#18b4ed"));
                            tvCSale.setCompoundDrawables(null, cSale, null, null);
                        }
                        if (string.contains("运营")) {
                            tvCOper.setTextColor(Color.parseColor("#18b4ed"));
                            tvCOper.setCompoundDrawables(null, cOper, null, null);
                        }
                    }

                    //TODO 修改
                    tvTeamers.setText(project.getTeamer());
                    final List<String> data = StringUtils.getDirsValues(ProjectDetailActivity.this);
                    tvDir.setText(data.get(project.getDir() - 1001));
                    tvProgress.setText(project.getProgress());
                    Picasso.with(ProjectDetailActivity.this)
                            .load(project.getLogo())
                            .placeholder(R.mipmap.project_default)
                            .into(cvLogo);

                    if (project.getUser_id() != AppContext.getInstance().getUserId() && project.getJlq_id() != 0) {
                        //不是当前用户自己的项目可点击加入
                        tvJlq.setText(project.getJlq_name());
                        tvJlq.setVisibility(View.VISIBLE);
                        tvJlq.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Bundle bundle = new Bundle();
                                bundle.putInt("id", project.getJlq_id());
                                bundle.putString("qun", "yes");
                                bundle.putString("name", project.getJlq_name());
                                UIHelper.showActivity(ProjectDetailActivity.this, TlzDetailActivity.class, bundle);
                            }
                        });
                    } else if (project.getUser_id() == AppContext.getInstance().getUserId() && project.getJlq_id() == 0) {
                        //是自己的项目且还没有项目群
                        //点击去创建
//                        tvJlq.setText("点击创建我的项目群");
//                        tvJlq.setVisibility(View.VISIBLE);
//                        tvJlq.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                UIHelper.showActivity(ProjectDetailActivity.this, NewJlqActivity.class);
//                    }
//                        });
                    }


                    break;
                case CHECK_YES_ATTENTION:
                    ivCollect.setSelected(true);
                    collected = true;
                    break;
                case CHECK_NO_ATTENTION:
                    ivCollect.setSelected(false);
                    collected = false;
                    break;
            }
        }
    };

    /**
     * 初始化界面
     */
    private void initView() {

        tvName = (TextView) findViewById(R.id.tv_project_detail_name);
        tvLocation = (TextView) findViewById(R.id.tv_project_detail_location);
        tvDate = (TextView) findViewById(R.id.tv_project_detail_date);
        tvAttention = (TextView) findViewById(R.id.tv_project_detail_attention);
        tvComments = (TextView) findViewById(R.id.tv_project_detail_comment);
        llInfo = (CheckBox) findViewById(R.id.cb_project_detail_info);
        llPartner = (CheckBox) findViewById(R.id.cb_project_detail_partner);
        vInfo = (TextView) findViewById(R.id.v_bootom_blue_project_detail_info);
        vPartner = (TextView) findViewById(R.id.v_bootom_blue_project_detail_partner);
        /*合伙人信息*/
        tvCTech = (TextView) findViewById(R.id.tv_project_detail_call_tec);
        tvCProduct = (TextView) findViewById(R.id.tv_project_detail_call_product);
        tvCOper = (TextView) findViewById(R.id.tv_project_detail_call_oper);
        tvCDesign = (TextView) findViewById(R.id.tv_project_detail_call_design);
        tvCSale = (TextView) findViewById(R.id.tv_project_detail_call_sale);
        lvTeamer = (ScrollXListView) findViewById(R.id.slv_project_detail_teamer);
        lvTeamer.setPullLoadEnable(false);
        lvTeamer.setPullRefreshEnable(false);
        lvTeamer.setVerticalScrollBarEnabled(false);
        tvJlq = (TextView) findViewById(R.id.tv_project_detail_jlq);
        tvJlq.setVisibility(View.GONE);
        /*详细信息*/
        tvIntro = (TextView) findViewById(R.id.tv_project_detail_intro);
        tvTeamers = (TextView) findViewById(R.id.tv_project_detail_teamers);
        tvDir = (TextView) findViewById(R.id.tv_project_detail_dir);
        tvProgress = (TextView) findViewById(R.id.tv_project_detail_progress);
        tvDetail = (TextView) findViewById(R.id.tv_project_detail_detail);
        ivBack = (ImageView) findViewById(R.id.header_iv_back);
        ivCollect = (ImageView) findViewById(R.id.iv_project_detail_collect);
        ivCollect.setOnClickListener(this);
        cvLogo = (CircleImageView) findViewById(R.id.cv_project_detail_logo);
        llComment = (LinearLayout) findViewById(R.id.ll_project_detail_comment);
        llAttention = (LinearLayout) findViewById(R.id.ll_project_detail_attention);

        svInfo = (ScrollView) findViewById(R.id.sv_project_detail_info);
        svPartner = (ScrollView) findViewById(R.id.sv_project_detail_partner);

        cTech = getResources().getDrawable(R.mipmap.calls_tech);
        cTech.setBounds(0, 0, cTech.getMinimumWidth(), cTech.getMinimumHeight());
        cProduct = getResources().getDrawable(R.mipmap.calls_product);
        cProduct.setBounds(0, 0, cProduct.getMinimumWidth(), cProduct.getMinimumHeight());
        cOper = getResources().getDrawable(R.mipmap.calls_operation);
        cOper.setBounds(0, 0, cOper.getMinimumWidth(), cOper.getMinimumHeight());
        cSale = getResources().getDrawable(R.mipmap.calls_sale);
        cSale.setBounds(0, 0, cSale.getMinimumWidth(), cSale.getMinimumHeight());
        cDesign = getResources().getDrawable(R.mipmap.calls_design);
        cDesign.setBounds(0, 0, cDesign.getMinimumWidth(), cDesign.getMinimumHeight());

        selectIndex(1);
    }

    private void selectIndex(int i) {
        if (i == 1) {
            //详细信息
            vInfo.setVisibility(View.VISIBLE);
            vPartner.setVisibility(View.INVISIBLE);
            svInfo.setVisibility(View.VISIBLE);
            svPartner.setVisibility(View.GONE);

            llInfo.setChecked(true);
            llPartner.setChecked(false);
        } else if (i == 2) {
            //合伙人
            vInfo.setVisibility(View.INVISIBLE);
            vPartner.setVisibility(View.VISIBLE);
            svInfo.setVisibility(View.GONE);
            svPartner.setVisibility(View.VISIBLE);

            llInfo.setChecked(false);
            llPartner.setChecked(true);
        }
    }

    /**
     * 初始化监听器
     */
    private void initListeners() {
        llComment.setOnClickListener(this);
        llAttention.setOnClickListener(this);

        ivBack.setOnClickListener(this);
        ivCollect.setOnClickListener(this);

        llInfo.setOnClickListener(this);
        llPartner.setOnClickListener(this);

        lvTeamer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < 1) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putInt("userId", project.getTeamers().get(position - 1).getUser_id());
                UIHelper.showActivity(ProjectDetailActivity.this, UserInfoActivity.class, bundle);
            }
        });
    }

    private boolean collected = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.header_iv_back:
                finish();
                break;
            case R.id.iv_project_detail_collect:
                //收藏
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(ProjectDetailActivity.this);
                    return;
                }
                if (collected) {
                    ThreadPoolUtils.execute(new Runnable() {
                        @Override
                        public void run() {
                            projectService.doAttention(pId, false);
                            handler.sendEmptyMessage(CHECK_NO_ATTENTION);
                        }
                    });
                } else {
                    ThreadPoolUtils.execute(new Runnable() {
                        @Override
                        public void run() {
                            projectService.doAttention(pId, true);
                            handler.sendEmptyMessage(CHECK_YES_ATTENTION);
                        }
                    });
                }
                break;
            case R.id.ll_project_detail_comment:
                //评论页
                Bundle bundle1 = new Bundle();
                bundle1.putInt("pId", pId);
                UIHelper.showActivity(ProjectDetailActivity.this, ProjectCommentActivity.class, bundle1);
                break;
            case R.id.ll_project_detail_attention:
                //关注列表
                Bundle bundle2 = new Bundle();
                bundle2.putInt("pId", pId);
                UIHelper.showActivity(ProjectDetailActivity.this, ProjectAttentionedActivity.class, bundle2);
                break;
            case R.id.cb_project_detail_info:
                //关注列表
                selectIndex(1);
                break;
            case R.id.cb_project_detail_partner:
                //关注列表
                selectIndex(2);
                break;
        }
    }

}
